/* 走线上 */
import aspNet from './asp.net.js'
import $axios from 'axios'
import Ajax from './ajax-general'
import AjaxCache from './ajax-cache'
import each from '@/modules/corejs/each/each'

// 走 .net 代理 go 接口
const ajaxGo = new Ajax(null, aspNet)
// 直连 .net 接口
const ajax = new Ajax(function (data) {
  if (data.code === 0) {
    return data.data
  }
  return new Error(data.message)
})

const api = {
  campusId: null, // 校区id
  equipmentCode: null,
  templateid: null, // 当前模板id
  cache: {
    // classId: null
  },
  // 校牌
  classesByOverType () {
    return ajaxGo.get('/classcard/v1/classesByOverType', { params: { code: this.equipmentCode } })
  },
  getCache (name, get) {
    let ajaxCache = this.cache[name]
    if (!ajaxCache) ajaxCache = this.cache[name] = new AjaxCache(get)
    return ajaxCache.request()
  },
  // 缓存到自身 api
  getSelfCache (name, get) {
    let ajaxCache = this.cache[name]
    if (!ajaxCache) ajaxCache = this.cache[name] = new AjaxCache(get)
    return ajaxCache.request()
  },
  // getClassData (code = this.equipmentCode) {
  //   return this.getCache('classData', () => ajax.post('/Mccard/ClassBrand/GetGroupEditModel', { code }))
  // },
  getClassId () {
    return this.getCache('classData', () => ajax.post('/Mccard/ClassBrand/GetGroupEditModel', { code: this.equipmentCode }).then(classData => {
      if (classData) {
        return (this.classId = classData.id)
      }
      throw new Error(new Error('classId 获取失败'))
    }))
  },
  ajaxGetComm (name) {
    return this.getClassId().then(classId => {
      return ajaxGo.get(`/classcard/v1/${name}/${classId}`)
    })
  },
  // 消息通知
  getNoticeByEquipmentCode (priority) {
    return ajax.get(`/Mccard/Ajax/GetNoticeByEquipmentCode?priority=${priority}&equipmentCode=` + this.equipmentCode)
  },

  getClassInfo () {
    return this.ajaxGetComm('getClassInfo')
  },
  // true 则不需要 classId
  getSchoolLogo (noClass) {
    if (noClass) {
      return ajaxGo.get(`/classcard/v1/getSchoolLogo?code=${this.equipmentCode}`)
    }
    return this.getClassId().then(classId => {
      return ajaxGo.get(`/classcard/v1/getSchoolLogo?class_id=${classId}&code=${this.equipmentCode}`)
    })
  },
  getDreamHorse () {
    return this.ajaxGetComm('getDreamHorse')
  },
  getBeautifulStars () {
    return this.ajaxGetComm('getBeautifulStars')
  },
  getClassProfile () {
    return this.ajaxGetComm('getClassProfile')
  },
  // 获取最新公告
  proclamation () {
    return this.getClassId().then(() => {
      return ajaxGo.get(`/classcard/v1/proclamation/${this.campusId}`)
    })
  },
  // 校区所有班级的美星荣誉
  getBeautifulStarsOfACampus (periodType) {
    return this.getClassId().then(() => {
      return ajaxGo.get(`/classcard/v1/getBeautifulStarsOfACampus/${this.campusId}?period_type=${periodType}`)
    })
  },
  // 获取校区周荣誉称号及LOGO列表
  weekHonorNameAndImageList (periodType) {
    return this.getClassId().then(() => {
      return ajaxGo.get(`/classcard/v1/weekHonorNameAndImageList/${this.campusId}?period_type=${periodType}`)
    })
  },
  // 统计校区所有教师的授课和听课次数
  statsCoursesFrequenceOfACampus () {
    return this.getClassId().then(() => {
      return ajaxGo.get(`/lecture/v1/statsCoursesFrequenceOfACampus?campus_id=${this.campusId}&range_type=this_semester&offset=0&list_mun=10`)
    })
  },
  // 获取班级制度管理
  getClassRuleEventList (num = 3) {
    return this.getClassId().then(classId => {
      return ajaxGo.get(`/classcard/v1/getClassRuleEventList?class_id=${classId}&list_mun=${num}`)
    })
  },
  // 获取班级目标口号和寄语
  getClassTarget () {
    return this.ajaxGetComm('getClassTarget')
  },
  // 今日签到
  getSignInfo () {
    return this.ajaxGetComm('getSignInfo')
  },
  // 今日表现
  getClassRulePerf () {
    return this.ajaxGetComm('getClassRulePerf')
  },
  // 今日值日
  getDutyInfo () {
    return this.ajaxGetComm('getDutyInfo')
  },
  // 今日明日课表
  getCurriculums () {
    return this.ajaxGetComm('getCurriculums')
  },
  // 班级美少年
  getAdonises () {
    return this.ajaxGetComm('getAdonises')
  },
  // 特色活动、主题班会、安全教育、微阅读
  getASTM () {
    return this.ajaxGetComm('getASTM')
  },

  // 获取新的校园文化数据
  getDataTemp3 (id) {
    return ajax.get('/Mccard/ClassBrand/GetTemplate?templateId=' + id)
  },

  // ASTM 列表页面
  getListASTM (type) {
    return this.getClassId().then(classId => {
      return ajaxGo.get(`/classcard/v1/${type}?class_id=${classId}&begin=0&size=20`)
    })
  },
  // 文章页
  getArticle (type, id) {
    return ajaxGo.get(`/classcard/v1/${type}/${id}`)
  },

  // 获取校区宿舍数据
  getDormList () {
    return ajaxGo.get('/classcard/v1/getDormList?eq_code=' + this.equipmentCode).then(data => data.data)
  },
  // 获取宿舍行为数据
  getDormRules ({ areaId, dormId, range }) {
    let params = '?eq_code=' + this.equipmentCode + '&range_type=' + range
    if (areaId) params += '&building_id=' + areaId
    if (dormId) params += '&dorm_id=' + dormId
    return ajaxGo.get('/classcard/v1/getDormRules' + params).then(data => {
      return data.data.map(item => {
        return {
          id: item.event_id,
          no: item.building_name + '/' + item.dorm_name,
          name: item.user_name,
          rules: item.rule_items.map(rule => rule.item_name).join('/'),
          score: item.score,
          date: this.datatimeFormat(item.event_date)
        }
      })
    })
  },

  // 验证视频url是否过时
  validityVideoToken (url) {
    return $axios.get(url).then(() => {
      return 0
    }).catch(() => {
      return 1
    })
  },
  // 拿带 token 的视频 url
  getPlayDownloadUrl (url) {
    return ajax.get('/Mccard/ClassBrand/GetPlayDownloadUrl?url=' + url)
  },

  // 日期时间简单格式化。格式化此种格式的日期：
  // 2019-04-22T12:35:00+08:00
  // 2019-04-22 12:35:00 去掉秒
  datatimeFormat (datatime) {
    return datatime
      .replace(/T/, ' ').replace(/:\d\d(\+.+)*$/, '')
      // .replace(/(.+?)\s?(\d\d:\d\d.*)/, '$1 $2') // ios 特殊空格不识别问题
  },

  // 缓存资源 data-resources
  cacheResources (baseCacheData) {
    // let path = 'file:///data-resources/'
    let path = 'data-resources/'
    let resources = []
    let reg = /http:\/\/.+\//

    function httpHandle (url) {
      if (url) {
        resources.push(url)
        return url.replace(reg, path)
      }
      return url
    }

    try {
      each(baseCacheData.getASTM, d => {
        let urlKey = d.url === undefined ? 'img_url' : 'url'
        d[urlKey] = httpHandle(d[urlKey])
      })

      each(baseCacheData.getAdonises, (d, k) => {
        if (k === 'group_week_winner') {
          d.win_url = httpHandle(d.win_url)
        } else if (k === 'stared_students') {
          d.forEach(n => {
            n.url = httpHandle(n.url)
          })
        }
      })
    } catch (error) {
      console.error(error)
    }

    each(baseCacheData.getArticle, d => {
      try {
        let { data } = d
        let urlKey = data.url === undefined ? 'img_url' : 'url'
        data[urlKey] = httpHandle(data[urlKey])
      } catch (e) {
        console.error(e)
      }
    })

    try {
      // 美星美誉
      baseCacheData.getBeautifulStars.data.forEach(d => {
        d.image = httpHandle(d.image)
      })

      let data = baseCacheData.getClassProfile.data
      data.photo_url = httpHandle(data.photo_url)
    } catch (e) {
      console.error(e)
    }

    try {
      // 梦马
      let data = baseCacheData.getDreamHorse.data[0]
      if (data) data.image = httpHandle(data.image)
    } catch (e) {
      console.error(e)
    }

    try {
      // 列表
      each(baseCacheData.getListASTM, d => {
        d.data.forEach(d => {
          let urlKey = d.url === undefined ? 'img_url' : 'url'
          d[urlKey] = httpHandle(d[urlKey])
        })
      })
    } catch (error) {
      console.error(error)
    }

    try {
      let data = baseCacheData.getSchoolLogo.data
      data.logo_url = httpHandle(data.logo_url)
    } catch (e) {
      console.error(e)
    }

    return resources
  },
  // 所有文章页
  cacheArticle (baseCacheData) {
    return new Promise(resolve => {
      let cacheData = {}
      let { getListASTM } = baseCacheData
      let listTypes = ['getActivityList', 'getSafetyEduList', 'getThemeMeetingList', 'getMicroReadList']
      let types = ['getActivityDetail', 'getSafetyEduDetail', 'getThemeMeetingDetail', 'getMicroReadDetail']

      let count = 0
      listTypes.forEach((listType, i) => {
        let list = getListASTM[listType]
        let type = types[i]
        count += list.count
        list.data.forEach(d => {
          let id = d.id
          this.getArticle(type, id).catch(err => err).then(data => {
            cacheData[type + id] = data
            if (--count === 0) {
              baseCacheData['getArticle'] = cacheData
              resolve()
            }
          })
        })
      })
      if (count === 0) { // 没有任何文章直接回调
        resolve()
      }
    })
  },

  // 所有列表页缓存
  cacheListASTM (baseCacheData) {
    return new Promise(resolve => {
      let cacheData = {}
      let count = 4;
      ['getActivityList', 'getSafetyEduList', 'getThemeMeetingList', 'getMicroReadList'].forEach(type => {
        this.getListASTM(type).then(data => {
          cacheData[type] = data
          if (--count === 0) {
            baseCacheData['getListASTM'] = cacheData
            this.cacheArticle(baseCacheData).then(() => {
              resolve()
            })
          }
        })
      })
    })
  },
  // 缓存所有
  cacheAll () {
    if (!window.jselectronic) return // 没有缓存接口直接跳出

    let reqList = [
      'getClassRuleEventList',
      'getClassTarget',
      'getClassInfo',
      'getSchoolLogo',
      'getDreamHorse',
      'getBeautifulStars',
      'getClassProfile',
      'getSignInfo',
      'getClassRulePerf',
      'getDutyInfo',
      'getCurriculums',
      'getAdonises',
      'getASTM'
    ]

    let cacheData = {
      templateid: this.templateid
    }

    let count = reqList.length
    reqList.forEach(req => {
      // this.ajaxGetComm(req).then(data => {
      this[req]().then(data => {
        cacheData[req] = data
      }).catch(() => {
        cacheData[req] = { data: {} }
      }).then(() => {
        // 接口模拟
        if (process.env.NODE_ENV !== 'production') {
          window.jselectronic = {
            savaJsonData (d) {
              console.log('保存json成功', d)
            },
            saveResources () {
              console.log('保存资源成功')
            }
          }
        }
        if (--count === 0) {
          // 开始缓存ASTM列表+文章
          this.cacheListASTM(cacheData).then(() => {
            let resources = this.cacheResources(cacheData) // 缓存图片等资源
            // 保存
            window.jselectronic.savaJsonData(`window.jsonp_send(${JSON.stringify(cacheData)})`) // data.json
            window.jselectronic.saveResources(JSON.stringify(resources)) // data-assets
          })
        }
      })
      // this[req]().then
    })
  }
}

export default api
